#!/bin/bash

SSID=${WIFI_SSID:-"AI200"}
PASSWORD=${WIFI_PASSWORD:-"hanweiai"}

echo "WiFi test starting for SSID: $SSID"

# Step 1: Down interface
ip link set wlan0 down

# Step 2: 启动 wpa_supplicant
wpa_supplicant -B -i wlan0 -c <(cat <<EOF
ctrl_interface=/var/run/wpa_supplicant
update_config=1
network={ssid="$SSID" psk="$PASSWORD"}
EOF
)

sleep 2

# Step 3: 获取 IP（带超时）
if ! timeout 10 dhclient wlan0; then
    echo "Failed to get IP address."
    killall wpa_supplicant
    ip link set wlan0 down
    echo "wifi 测试失败"
    exit 1
fi

# Step 4: 快速 ping 测试
if ping -c 2 -W 3 223.5.5.5 > /dev/null; then
    echo "WiFi test successful"
    echo "$(date)：WiFi测试成功" >> /userfs/all.txt
    echo "wifi 测试成功"
else
    echo "Internet unreachable after connect."
    echo "wifi 测试失败"
fi

# 清理
killall wpa_supplicant
dhclient -r wlan0
ip link set wlan0 down